//登录与注册的仓库
import Vue from "vue";
import Vuex from "vuex";
import {getUserInfo, reqGetCode, reqLogin, reqUserRegister} from "@/api";

Vue.use(Vuex);

// 数据
let state = {
    code:[], //验证码
    token:localStorage.getItem('TOKEN'),
    userInfo:{}
};

// 写好逻辑后，提交给mutations处理修改数据
let actions = {
    // 请求验证码
    async reqGetCode(context,params){
        let result = await reqGetCode(params);
        if ((result.data.code == 200)) {
            context.commit('REQGETCODE',result.data.data);
        }else {
            return Promise.reject(new Error(result.data.message));
        }
    },
    // 请求用户注册
    async reqUserRegister(context,params){
        let result = await reqUserRegister(params);
        if ((result.data.code == 200)) return 'ok';else {
            return Promise.reject(new Error(result.data.message));
        }
    },
    // 请求用户登录
    async reqLogin(context,params){
        let result = await reqLogin(params);
        context.commit('REQLOGIN',result.data.data.token);
        localStorage.setItem('TOKEN',result.data.data.token);
        if ((result.data.code == 200)) return 'ok';else {
            return Promise.reject(new Error(result.data.message));
        }
    },
    // 请求用户信息
    async getUserInfo(context,params){
        let result = await getUserInfo();
        context.commit('GETUSERINFO',result.data.data)
        if ((result.data.code == 200)) return 'ok';else {
            return Promise.reject(new Error(result.data.message));
        }
    },

};

// 只有mutations能够修改数据
let mutations = {
    REQGETCODE(state,value){
        state.code = value;
    },
    REQLOGIN(state,value){
        state.token = value;
    },
    GETUSERINFO(state,value){
        state.userInfo = value;
    }

};

// 优化数据结构，过滤数据
let getters = {

};


export default {
    namespaced:true,
    state,
    mutations,
    actions,
    getters
}
